{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    {% block title %}
        <title>高级查询</title>
    {% endblock %}
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 引入bootstrap的css文件 -->
    <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">

    <!-- 引入datatables的css文件 -->
    <link rel="stylesheet" href="{% static 'DataTables/datatables.min.css' %}"/>
    <link rel="stylesheet" href="{% static 'Buttons/css/buttons.dataTables.min.css' %}">
    <link rel="stylesheet" href="{% static 'stylesheets/rowReorder.dataTables.min.css' %}">
    <link rel="stylesheet" href="{% static 'stylesheets/colReorder.dataTables.min.css' %}">
    <link rel="stylesheet" href="{% static 'stylesheets/fixedColumns.dataTables.min.css' %}">
    <link rel="stylesheet" href="{% static 'stylesheets/select.dataTables.min.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-ui/jquery-ui.css' %}">

    <!-- 引入自定义的css样式-->
    <style type="text/css">
        .dropdown-menu a:hover {
            color: #fff;
            background-color: #17a2b8;
            border-color: #fff;
        }

        .checkbox-lg input[type=checkbox] {
            width: 26px;
            height: 26px;
            border: 2px solid;
            border-radius: 5px;
            /*checkbox border color*/
            border-color: #737373;
        }

        .checkbox-lg input[type=checkbox]:checked {
            width: 26px;
            height: 26px;
            /*checkmark arrow color*/
            border: solid white;
            border-width: 0 3px 3px 0;
        }
    </style>
</head>

<body>
<div class="container-fluid">
    <nav class="navbar navbar-expand-lg bg-info navbar-dark">
        <a class="navbar-brand" style="padding: 0 10px;">BGI</a>
        <ul class="nav navbar-nav">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="navbardrop" data-toggle="dropdown"
                   style="margin: 0 20px">样本管理</a>
                <div class="dropdown-menu">
                    <a class="dropdown-item" href="{% url 'Main_model' re_model='Clinical' %}">样本临床信息</a>
                    <a class="dropdown-item" href="{% url 'Main_model' re_model='Extract' %}">样本DNA提取信息</a>
                    <a class="dropdown-item" href="{% url 'Main_model' re_model='DNAUsageRecord' %}">样本DNA使用记录</a>
                    <a class="dropdown-item" href="{% url 'Main_model' re_model='DNAInventory' %}">样本DNA库存</a>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="navbardrop" data-toggle="dropdown"
                   style="margin: 0 20px">文库管理</a>
                <div class="nav-link navbar-collapse" id="collapsibleNavbar1">
                    <div class="dropdown-menu">
                        <a class="dropdown-item" href="{% url 'Main_model' re_model='Library' %}">样本建库信息</a>
                        <a class="dropdown-item" href="{% url 'Main_model' re_model='Capture' %}">捕获文库信息</a>
                        <a class="dropdown-item" href="{% url 'Main_model' re_model='Pooling' %}">Pooling映射</a>
                    </div>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="navbardrop" data-toggle="dropdown"
                   style="margin: 0 20px">测序管理</a>
                <div class="nav-link navbar-collapse" id="collapsibleNavbar1">
                    <div class="dropdown-menu">
                        <a class="dropdown-item" href="{% url 'Main_model' re_model='Sequencing' %}">测序上机信息</a>
                        <a class="dropdown-item" href="{% url 'Main_model' re_model='QC' %}">样本测序质控信息</a>
                    </div>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="navbardrop" data-toggle="dropdown"
                   style="margin: 0 20px">高级功能</a>
                <div class="nav-link navbar-collapse" id="collapsibleNavbar1">
                    <div class="dropdown-menu">
                        <a class="dropdown-item" href="{% url 'AdvanceUpload' %}">订制批量上传</a>
                        <a class="dropdown-item" href="{% url 'AdvancedSearch' %}">高级自主查询</a>
                        <a class="dropdown-item" href="#">预订制查询</a>
                    </div>
                </div>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" id="navbardrop" data-toggle="dropdown"
                   style="margin: 0 20px">用户管理</a>
                <div class="nav-link navbar-collapse" id="collapsibleNavbar1">
                    <div class="dropdown-menu">
                        <a class="dropdown-item" href="{% url 'index' %}">登录/注册</a>
                        <a class="dropdown-item" href="{% url 'user_info' %}">用户信息</a>
                        <a class="dropdown-item" href="{% url 'logout' %}">退出</a>
                    </div>
                </div>
            </li>

        </ul>
    </nav>

    {% block content %}
        <div class="jumbotron">
            <h1>甲基化早筛项目数据库管理系统Demo</h1>
            <h4>高级查询</h4><br>
            <form id="searchForm1" role="form">
                <div class="form-group">
                    <p class="bg-info text-white">
                        &nbsp;&nbsp<label class="text-white h4" for="searchModels"> 查询表</label>
                    </p>
                    <div>
                        <div class="h6"><span>样本管理  </span>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchClinicalInfo"
                                       value="ClinicalInfo" name="searchModels" checked> 样本临床信息
                            </label>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchExtractInfo"
                                       value="ExtractInfo" name="searchModels"> 样本DNA提取信息
                            </label>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchDNAUsageRecordInfo"
                                       value="DNAUsageRecordInfo" name="searchModels"> 样本DNA使用记录
                            </label>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchDNAInventoryInfo"
                                       value="DNAInventoryInfo" name="searchModels"> 样本DNA库存
                            </label>
                        </div>
                        <br>
                        <div class="h6"><span>文库管理  </span>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchLibraryInfo"
                                       value="LibraryInfo" name="searchModels"> 样本建库信息
                            </label>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchCaptureInfo"
                                       value="CaptureInfo" name="searchModels"> 捕获文库信息
                            </label>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchPoolingInfo"
                                       value="PoolingInfo" name="searchModels"> Pooling映射表
                            </label>
                        </div>
                        <br>
                        <div class="h6"><span>测序管理  </span>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchSequencingInfo"
                                       value="SequencingInfo" name="searchModels"> 测序上机信息
                            </label>&nbsp;&nbsp
                            <label class="checkbox-inline checkbox-lg">
                                <input type="checkbox" id="searchQCInfo"
                                       value="QCInfo" name="searchModels"> 样本测序质控信息
                            </label>
                        </div>
                    </div>
                </div>
                <button type="button" class="btn btn-light h6" id="tableSet1">选取样本管理表集合</button>&nbsp;
                <button type="button" class="btn btn-light h6" id="tableSet2">选取文库管理表集合</button>&nbsp;
                <button type="button" class="btn btn-light h6" id="tableSet3">选取测序管理表集合</button>&nbsp;
                <button type="button" class="btn btn-light h6" id="tableSet4">选取所有表</button>
            </form>
            <br>

            <form id="searchForm2" role="form">
                <p class="bg-info text-white">
                    &nbsp;&nbsp <label class="text-white h4" for="SearchText"> 设置过滤条件</label></p>
                <div class="form-inline mb-1">
                    <button id='textareaAdd' class="btn btn-primary h6">确认过滤条件</button>&nbsp;&nbsp
                    <button id='conditionAdd' class="btn btn-info h6">添加过滤条件</button>
                </div>
                <br>
                <div class="form-inline search_condition" id="condition1">
                    <span class="text-info h6">过滤条件1</span>&nbsp;&nbsp;<div class="form-group">
                    <label for="SearchNot1" class="bg-info text-white badge badge-primary"></label>
                    <select class="form-control SearchNot" id="SearchNot1" name="SearchNot1" required="true">
                        <option value="0" selected="selected"></option>
                        <option value="1">非</option>
                    </select>
                </div>&nbsp;&nbsp
                    <div class="form-group">
                        <label for="SearchModelName1" class="bg-info text-white h6">查询子表
                        </label>&nbsp;&nbsp
                        <select class="form-control SearchModelName" id="SearchModelName1" name="SearchModelName1"
                                required="true">
                        </select>
                    </div>&nbsp;&nbsp
                    <div class="form-group">
                        <label for="SearchFieldName1" class="bg-info text-white h6">查询字段
                        </label>&nbsp;&nbsp
                        <select class="form-control SearchFieldName" id="SearchFieldName1" name="SearchFieldName1"
                                required="true">
                        </select>
                    </div>&nbsp;&nbsp
                    <div class="form-group">
                        <label for="SearchFieldValue1" class="bg-info text-white h6">查询字段值
                        </label>&nbsp
                        <select class="form-control SearchFieldValuePre" id="SearchFieldValuePre1"
                                name="SearchFieldValuePre1" required="true">
                            <option value="exact" selected="selected">等于(大小写严格匹配)</option>
                            <option value="iexact">等于(忽略大小写)</option>
                            <option value="contains">包含(大小写严格匹配)</option>
                            <option value="icontains">包含(忽略大小写)</option>
                            <option value="gt">大于</option>
                            <option value="gte">大于等于</option>
                            <option value="lt">小于</option>
                            <option value="lte">小于等于</option>
                        </select>&nbsp

                        <input type="text" class="form-control SearchFieldValue" id="SearchFieldValue1"
                               name="SearchFieldValue1" placeholder="请输入查询字段值">

                    </div>
                </div>
            </form>
            <br>
            <form id="searchForm3" role="form">
                {% csrf_token %}
                <div class="form-group">
                    <p class="bg-info text-white">
                        &nbsp;&nbsp <label class="text-white h4" for="SearchText"> 过滤条件如下:</label></p>
                    <textarea class="form-control" rows="3" id="SearchText" name="SearchText"></textarea>
                </div>
                <button id='textareaSubmit' type="submit"
                        class="btn btn-primary">查询
                </button>
                <button id='textareaClear' type="button" class="btn btn-danger">清除</button>
            </form>
        </div>
    {% endblock %}

    {% block plot %}

    {% endblock %}

    {% block button %}

    {% endblock %}

    {% block table %}
        <!-- datatables -->
        <div id="resetTable">
        </div>
    {% endblock %}

</div>

<!-- bootstrap.js 依赖 jquery.js 和popper.js，因此在这里引入 -->
<script src="{% static 'jquery/jquery.min.js' %}"></script>
<script src="{% static 'popper/popper.min.js' %}"></script>
<!-- 引入bootstrap的js文件 -->
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<!-- 引入datatables的js文件 -->
<script src="{% static 'js/pdfmake.min.js' %}"></script>
<script src="{% static 'js/vfs_fonts.js' %}"></script>
<script src="{% static 'DataTables/datatables.min.js' %}"></script>
<script src="{% static 'Buttons/js/dataTables.buttons.min.js' %}"></script>
<script src="{% static 'js/jszip.min.js' %}"></script>
<script src="{% static 'Buttons/js/buttons.colVis.min.js' %}"></script>
<script src="{% static 'Buttons/js/buttons.html5.min.js' %}"></script>
<script src="{% static 'js/dataTables.select.min.js' %}"></script>
<script src="{% static 'js/dataTables.rowReorder.min.js' %}"></script>
<script src="{% static 'js/dataTables.colReorder.min.js' %}"></script>
<script src="{% static 'js/dataTables.fixedColumns.min.js' %}"></script>
<script src="{% static 'Highcharts/highcharts.js' %}"></script>
<script src="{% static 'Highcharts/highcharts-more.js' %}"></script>
<script src="{% static 'jquery-ui/jquery-ui.js' %}"></script>

<script>
    $.ajaxSetup({
        headers: {"X-CSRFToken": '{{csrf_token}}'}
    });

    function changeThreeDecimal_f(x) {
        var f_x = parseFloat(x);
        if (isNaN(f_x)) {
            alert('function:changeTwoDecimal->parameter error');
            return false;
        }
        var f_x = Math.round(x * 1000) / 1000;
        var s_x = f_x.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + 3) {
            s_x += '0';
        }
        return s_x;
    }

    function pie_plot(model, field_value, field_text) {
        let ajax_data_dict = $.ajax({
            url: "{% url 'plot_data' %}",
            data: {
                model: model, field: field_value
            },
            dataType: 'json',
            contentType: "application/json",
            method: "GET",
            async: false
        }).responseJSON;
        let chart = {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
        };
        let title = {
            text: field_text + '占比图 (总数: ' + ajax_data_dict.sum + ')',
            style: {
                fontWeight: "bold"
            }
        };
        let tooltip = {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        };
        let plotOptions = {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: false
                },
                showInLegend: true
            }
        };

        let ajax_data_array = [];
        $.each(ajax_data_dict.data, function (k, v) {
            ajax_data_array.push([k, v]);
        });
        let series = [{
            type: 'pie',
            name: '占比',
            data: ajax_data_array
        }];
        let credits = {
            enabled: false,
            text: ''
        };
        let json = {};
        json.chart = chart;
        json.title = title;
        json.tooltip = tooltip;
        json.series = series;
        json.plotOptions = plotOptions;
        json.credits = credits;

        $('#plot_highcharts').highcharts(json);
    }

    String.format = function (src) {
        if (arguments.length === 0) return null;
        let args = Array.prototype.slice.call(arguments, 1);
        return src.replace(/\{(\d+)\}/g, function (m, i) {
            return args[i];
        });
    };
</script>

{% block button_js %}

{% endblock %}

{% block extra_js %}
    <script>
        $(document).ready(function () {
            for (let i = 2; i <= 10; i++) {
                let str = '<div class="form-inline search_condition" id="condition' + i + '">';
                str += '<span class="text-info h6">过滤条件' + i + '</span>&nbsp;&nbsp;<div class="form-group">' +
                    '<label for="SearchNot' + i + '" class="bg-primary text-white badge badge-info"></label>' +
                    '<select class="form-control SearchNot" id="SearchNot' + i + '" name="SearchNot' + i
                    + '"><option value="0" selected="selected"></option><option value="1">非' +
                    '</option></select></div>&nbsp;&nbsp;';
                str += '<div class="form-group"><label for="SearchModelName' + i + '" class="bg-info text-white ' +
                    'badge badge-primary h6">查询子表</label>&nbsp;&nbsp<select class="form-control ' +
                    'SearchModelName" id="SearchModelName' + i + '" name="SearchModelName' + i + '"></select>' +
                    '</div>&nbsp;&nbsp;';
                str += '<div class="form-group"><label for="SearchFieldName' + i + '" class="bg-info text-white ' +
                    'badge badge-primary h6">查询字段</label>&nbsp;&nbsp<select class="form-control ' +
                    'SearchFieldName" id="SearchFieldName' + i + '" name="SearchFieldName' + i + '"></select>' +
                    '</div>&nbsp;&nbsp;';
                str += '<div class="form-group"><label for="SearchFieldValue' + i + '" class="bg-info text-white ' +
                    'badge badge-primary h6">查询字段值</label>&nbsp<select class="form-control ' +
                    'SearchFieldValuePre" id="SearchFieldValuePre' + i + '" name="SearchFieldValuePre' + i +
                    '" required="true"><option value="exact" selected="selected">等于(大小写严格匹配)</option>' +
                    '<option value="iexact">等于(忽略大小写)</option><option value="contains">包含(大小写严格匹配)' +
                    '</option><option value="icontains">包含(忽略大小写)</option><option value="gt">大于</option>' +
                    '<option value="gte">大于等于</option><option value="lt">小于</option><option value="lte">小于等于' +
                    '</option></select>&nbsp;';
                str += '<input type="text" class="form-control SearchFieldValue" id="SearchFieldValue' + i + '" ' +
                    'name="SearchFieldValue' + i + '" placeholder="请输入查询字段值"></div></div>';
                $('#searchForm2').append(str);
                $('#condition' + i).hide();
            }
            // 选取样本管理表集合 按钮功能
            let click1 = 0;
            $('#tableSet1').click(function (e) {
                    e.preventDefault();
                    if (click1 === 0) {
                        click1 = 1;
                    } else {
                        click1 = 0;
                    }
                    $(this).button('toggle');
                    $(this).blur();
                    $.each(['ExtractInfo', 'DNAUsageRecordInfo', 'DNAInventoryInfo'], function (index_, value_) {
                        let str_ = '#search' + value_;
                        if (click1 === 0) {
                            $(str_).prop("checked", false);
                        } else {
                            $(str_).prop("checked", true);
                        }
                    });
                }
            );
            // 选取文库管理表集合 按钮功能
            let click2 = 0;
            $('#tableSet2').click(function (e) {
                    e.preventDefault();
                    if (click2 === 0) {
                        click2 = 1;
                    } else {
                        click2 = 0;
                    }
                    $(this).button('toggle');
                    $(this).blur();
                    $.each(['LibraryInfo', 'CaptureInfo', 'PoolingInfo'], function (index_, value_) {
                        let str_ = '#search' + value_;
                        if (click2 === 0) {
                            $(str_).prop("checked", false);
                        } else {
                            $(str_).prop("checked", true);
                        }
                    });
                }
            );
            // 选取测序管理表集合 按钮功能
            let click3 = 0;
            $('#tableSet3').click(function (e) {
                    e.preventDefault();
                    if (click3 === 0) {
                        click3 = 1;
                    } else {
                        click3 = 0;
                    }
                    $(this).button('toggle');
                    $(this).blur();
                    $.each(['SequencingInfo', 'QCInfo'], function (index_, value_) {
                        let str_ = '#search' + value_;
                        if (click3 === 0) {
                            $(str_).prop("checked", false);
                        } else {
                            $(str_).prop("checked", true);
                        }
                    });
                }
            );
            // 选取所有表集合 按钮功能
            let click4 = 0;
            $('#tableSet4').click(function (e) {
                    e.preventDefault();
                    if (click4 === 0) {
                        click4 = 1;
                    } else {
                        click4 = 0;
                    }
                    $(this).button('toggle');
                    $(this).blur();
                    $.each(['ExtractInfo', 'DNAUsageRecordInfo', 'DNAInventoryInfo', 'LibraryInfo',
                        'CaptureInfo', 'PoolingInfo', 'SequencingInfo', 'QCInfo'
                    ], function (index_, value_) {
                        let str_ = '#search' + value_;
                        if (click4 === 0) {
                            $(str_).prop("checked", false);
                        } else {
                            $(str_).prop("checked", true);
                        }
                    });
                }
            );
            // 查询子表下拉选框
            let models2label = {
                ClinicalInfo: '样本临床信息',
                ExtractInfo: '样本DNA提取信息',
                DNAUsageRecordInfo: '样本DNA使用记录',
                DNAInventoryInfo: '样本DNA库存',
                LibraryInfo: '样本建库信息',
                CaptureInfo: '捕获文库信息',
                PoolingInfo: 'Pooling映射表',
                SequencingInfo: '测序上机信息',
                QCInfo: '样本测序质控信息'
            };
            $('.search_condition .SearchModelName').focus(function () {
                // 获取想要查询的表
                $(this).empty();
                $(this).parents('.search_condition').find('.SearchFieldName').empty();
                $(this).parents('.search_condition').find('.SearchFieldValuePre').val('exact');
                $(this).parents('.search_condition').find('.SearchFieldValue').empty();
                let str = "";
                $("input[name='searchModels']:checked").each(function (i) {
                    let key_ = $(this).val();
                    str += '<option value="' + key_ +
                        '">' + models2label[key_] + '</option>';
                });
                $(this).append(str);

            });
            // 表格显示表头列名称
            let modelLabel = {
                'normal': {
                    'ClinicalInfo': ['姓名', '性别', '年龄', '住院号', '癌种', '分期', '诊断', '诊断备注',
                        '采样日期', '医院编号', '科室', '血浆管数', '癌旁组织样本数量', '癌组织样本数量',
                        '白细胞样本数量', '粪便样本数量', '寄送日期', '临床信息-备注'],
                    'ExtractInfo': ['提取日期', '样本类型', '样本体积(ml)', '提取方法', '浓度(ng/ul)', '体积(ul)',
                        '提取信息-备注'],
                    'DNAUsageRecordInfo': ['使用日期', '使用量', '用途', '建库编号(如有)', '使用记录-备注'],
                    'DNAInventoryInfo': ['DNA提取总量(ng)', '成功建库使用量(ng)', '失败建库使用量(ng)',
                        '科研项目使用量(ng)', '其他使用量(ng)', '剩余量(ng)'],
                    'LibraryInfo': ['管上编号', '是否临床', '文库名', '样本标签', 'index列表', '建库日期', '建库方法',
                        '试剂批次', '建库-起始量', '建库-PCR循环数', '建库-文库浓度', '建库-文库体积', '建库-操作人',
                        '建库信息-备注'],
                    'CaptureInfo': ['杂交日期', '杂交探针', '捕获文库-杂交时间(min)', '捕获文库-PostPCR循环数',
                        '捕获文库-PostPCR浓度(ng/ul)', '捕获文库-洗脱体积(ul)', '捕获文库-操作人', '捕获文库-备注'],
                    'PoolingInfo': ['pooling比例', 'pooling取样(ng)', 'pooling体积(ul)', 'pooling信息-备注'],
                    'SequencingInfo': ['送测日期', '上机时间', '下机时间', '测序-机器号', '测序-芯片号', '测序-备注'],
                    'QCInfo': ['QC编号', 'Data_Size(Gb)', 'Clean_Rate(%)', 'R1_Q20', 'R2_Q20', 'R1_Q30',
                        'R2_Q30', 'GC_Content', 'BS_conversion_rate(lambda_DNA)', 'BS_conversion_rate(CHH)',
                        'BS_conversion_rate(CHG)', 'Uniquely_Paired_Mapping_Rate', 'Mismatch_and_InDel_Rate',
                        'Mode_Fragment_Length(bp)', 'Genome_Duplication_Rate', 'Genome_Depth(X)',
                        'Genome_Dedupped_Depth(X)', 'Genome_Coverage', 'Genome_4X_CpG_Depth(X)',
                        'Genome_4X_CpG_Coverage', 'Genome_4X_CpG_methylation_level', 'Panel_4X_CpG_Depth(X)',
                        'Panel_4X_CpG_Coverage', 'Panel_4X_CpG_methylation_level', 'Panel_Ontarget_Rate(region)',
                        'Panel_Duplication_Rate(region)', 'Panel_Depth(site,X)', 'Panel_Dedupped_Depth(site,X)',
                        'Panel_Coverage(site,1X)', 'Panel_Coverage(site,10X)', 'Panel_Coverage(site,20X)',
                        'Panel_Coverage(site,50X)', 'Panel_Coverage(site,100X)', 'Panel_Uniformity(site,>20%mean)',
                        'Strand_balance(F)', 'Strand_balance(R)', 'GC_bin_depth_ratio', '质控-备注']
                },
                'link': {
                    'ClinicalInfo': ['样本编号'],
                    'ExtractInfo': ['样本编号', 'DNA提取编号'],
                    'DNAUsageRecordInfo': ['样本编号', 'DNA提取编号'],
                    'DNAInventoryInfo': ['样本编号', 'DNA提取编号'],
                    'LibraryInfo': ['样本编号', 'DNA提取编号', '建库编号'],
                    'CaptureInfo': ['捕获文库名'],
                    'PoolingInfo': ['样本编号', 'DNA提取编号', '建库编号', '捕获文库名', '测序文库名'],
                    'SequencingInfo': ['捕获文库名', '上机文库号'],
                    'QCInfo': ['样本编号', 'DNA提取编号', '建库编号', '捕获文库名', '测序文库名', '上机文库号']
                }
            };
            // 字典，用于构建request查询数据库，值与model的field一致
            let modelCol = {
                'normal': {
                    'ClinicalInfo': ['name', 'gender', 'age', 'patientId', 'category', 'stage', 'diagnose',
                        'diagnose_others', 'centrifugation_date', 'hospital', 'department', 'plasma_num',
                        'adjacent_mucosa_num', 'cancer_tissue_num', 'WBC_num', 'stool_num', 'send_date', 'others'],
                    'ExtractInfo': ['extract_date', 'sample_type', 'sample_volume', 'extract_method',
                        'dna_con', 'dna_vol', 'others'],
                    'DNAUsageRecordInfo': ['LB_date', 'mass', 'usage', 'singleLB_id', 'others'],
                    'DNAInventoryInfo': ['totalM', 'successM', 'failM', 'researchM', 'othersM', 'remainM'],
                    'LibraryInfo': ['tube_id', 'clinical_boolen', 'singleLB_name', 'label', 'barcodes', 'LB_date',
                        'LB_method', 'kit_batch', 'mass', 'pcr_cycles', 'LB_con', 'LB_vol', 'operator',
                        'others'],
                    'CaptureInfo': ['hybrid_date', 'probes', 'hybrid_min', 'postpcr_cycles', 'postpcr_con',
                        'elution_vol', 'operator', 'others'],
                    'PoolingInfo': ['pooling_ratio', 'mass', 'volume', 'others'],
                    'SequencingInfo': ['send_date', 'start_time', 'end_time', 'machine_id', 'chip_id', 'others'],
                    'QCInfo': ['QC_id', 'data_size_gb_field', 'clean_rate_field', 'r1_q20', 'r2_q20', 'r1_q30',
                        'r2_q30', 'gc_content', 'bs_conversion_rate_lambda_dna_field', 'bs_conversion_rate_chh_field',
                        'bs_conversion_rate_chg_field', 'uniquely_paired_mapping_rate', 'mismatch_and_indel_rate',
                        'mode_fragment_length_bp_field', 'genome_duplication_rate', 'genome_depth_x_field',
                        'genome_dedupped_depth_x_field', 'genome_coverage', 'genome_4x_cpg_depth_x_field',
                        'genome_4x_cpg_coverage', 'genome_4x_cpg_methylation_level', 'panel_4x_cpg_depth_x_field',
                        'panel_4x_cpg_coverage', 'panel_4x_cpg_methylation_level', 'panel_ontarget_rate_region_field',
                        'panel_duplication_rate_region_field', 'panel_depth_site_x_field',
                        'panel_dedupped_depth_site_x_field', 'panel_coverage_site_1x_field',
                        'panel_coverage_site_10x_field', 'panel_coverage_site_20x_field',
                        'panel_coverage_site_50x_field', 'panel_coverage_site_100x_field',
                        'panel_uniformity_site_20_mean_field', 'strand_balance_f_field', 'strand_balance_r_field',
                        'gc_bin_depth_ratio', 'others']
                },
                'link': {
                    'ClinicalInfo': ['sample_id'],
                    'ExtractInfo': ['sample_id', 'dna_id'],
                    'DNAUsageRecordInfo': ['sample_id', 'dna_id'],
                    'DNAInventoryInfo': ['sample_id', 'dna_id'],
                    'LibraryInfo': ['sample_id', 'dna_id', 'singleLB_id'],
                    'CaptureInfo': ['poolingLB_id'],
                    'PoolingInfo': ['sample_id', 'dna_id', 'singleLB_id', 'poolingLB_id', 'singleLB_Pooling_id'],
                    'SequencingInfo': ['poolingLB_id', 'sequencing_id'],
                    'QCInfo': ['sample_id', 'dna_id', 'singleLB_id', 'poolingLB_id', 'singleLB_Pooling_id', 'sequencing_id']
                }
            };
            // 查询字段名下拉选框
            $('.search_condition .SearchFieldName').focus(function () {
                // 获取想要查询的字段名
                $(this).empty();
                $(this).parents('.search_condition').find('.SearchFieldValuePre').val('exact');
                $(this).parents('.search_condition').find('.SearchFieldValue').empty();
                let key_ = $(this).parents('.search_condition').find('.SearchModelName').val();
                //alert(key_);
                let str = '';
                $.each(modelLabel['link'][key_], function (i, v) {
                    str += '<option value="' + modelCol['link'][key_][i] +
                        '">' + v + '</option>';
                });
                $.each(modelLabel['normal'][key_], function (i, v) {
                    str += '<option value="' + modelCol['normal'][key_][i] +
                        '">' + v + '</option>';
                });
                $(this).append(str);
            });
            // 查询字段值下拉选框

            $('#SearchFieldValue1').focus(function () {
                // 获取想要查询的字段值
                let key1 = $('#SearchModelName1').val();
                let key2 = $('#SearchFieldName1').val();
                let values = $.ajax({
                    url: "{% url 'unique' %}", data: {model: key1, filed: key2},
                    dataType: 'json', contentType: "application/json",
                    method: "GET", async: false
                }).responseJSON.values;
                console.info("key1:", key1, "key2:", key2, "values:", values, "values.length:", values.length);
                if (values.length === 0) {
                    console.log("empty list. do nothing");
                } else if (values.length > 10) {
                    values.push('...');
                    $(this).autocomplete({
                        autoFocus: true,
                        scroll: true,
                        minLength: 3,
                        delay: 10,
                        source: function (request, response) {
                            let matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
                            let max_match = 15;
                            let n_match = 0;
                            response($.grep(values, function (item) {
                                let flag_match = matcher.test(item);
                                if (item === "...") {
                                    return true;
                                } else if (flag_match && n_match <= max_match) {
                                    n_match += 1;
                                    return flag_match;
                                } else {
                                    return false;
                                }
                            }));
                        },
                        focus: function (event, ui) {
                            if (ui.item.label === "...") {
                                $(this).val("");
                            } else {
                                $(this).val(ui.item.label);
                            }
                            return false;
                        },
                        select: function (event, ui) {
                            if (ui.item.label === "...") {
                                $(this).val("");
                            } else {
                                $(this).val(ui.item.label);
                            }
                            return false;
                        }
                    });
                    console.log("if work");
                } else {
                    $(this).autocomplete({
                        autoFocus: true,
                        minLength: 0,
                        delay: 0,
                        source: values
                    }).autocomplete("search", "");
                    console.log("else work");
                }


            });


            //$('.search_condition .SearchFieldValue').focus(function () {
            // 获取想要查询的字段值
            //    $(this).empty();
            //    let key1 = $(this).parents('.search_condition').find('.SearchModelName').val();
            //    let key2 = $(this).parents('.search_condition').find('.SearchFieldName').val();
            //    let values = $.ajax({
            //        url: "{% url 'unique' %}", data: {model: key1, filed: key2},
            //        dataType: 'json', contentType: "application/json",
            //        method: "GET", async: false
            //    }).responseJSON.values;
            //    let str = '';
            //    $.each(values, function (index, value) {
            //        str += '<option value="' + value +
            //            '">' + value + '</option>';
            //    });
            //    $(this).append(str);
            //});

            // 实现"添加过滤条件"按钮的功能
            let conditionAdd = 1;
            $('#conditionAdd').click(function (e) {
                e.preventDefault();
                conditionAdd += 1;
                $('#condition' + conditionAdd).show();
                if (conditionAdd === 10) {
                    $('#conditionAdd').attr("disabled", true);
                }
            });


        })
    </script>
{% endblock %}

</body>

</html>